package cn.kevinproject.dingtalk_robot.datacenter;

import cn.kevinproject.dingtalk_robot.msg.FeedCardMessage;
import cn.kevinproject.dingtalk_robot.utils.ObjectMapperHolder;
import lombok.val;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kevin lau
 */
@Component("weibo")
public class WeiboHotDataGrab extends AbstractDataGrab {


    private final static String WEIBO_URL = "https://api.hmister.cn/weibo/";


    @Override
    public List<FeedCardMessage.Link> grabData() throws Exception {

        if (cache == null) {
            URL url = new URL(WEIBO_URL);
            WeiboData weiboData = ObjectMapperHolder.objectMapper.readValue(url.openStream(), WeiboData.class);
            if (weiboData == null || 200 != weiboData.getCode() || CollectionUtils.isEmpty(weiboData.getData())) {
                throw new RuntimeException("get data error");
            }
            cache = weiboData.getData().stream().map(t -> {
                val d = new FeedCardMessage.Link();
                d.setTitle(t.getName());
                d.setMessageUrl(t.getUrl());
                return d;
            }).limit(10).collect(Collectors.toList());
            cache.get(0).setPicUrl("https://image.kevinproject.cn/uPic/weibo.png");
        }
        return cache;
    }




}
